<template>
  <div>
    <my-breadcrumb :items="['商品管理', isAuditing ? '商品审核' : '商品信息修改']"></my-breadcrumb>
    <!--:initSpuData="initSpuData"-->
    <goods-spu @setImage="setImage" ref="goodsSpu"></goods-spu>
    <goods-sku @setImage="setImage" ref="goodsSku" :goodsId="goodsId"></goods-sku>
    <goods-rich-text ref="richText"></goods-rich-text>
    <Button long @click="finishAuditing" type="primary">{{ isAuditing ? '审核完成' : '修改完成' }}</Button>
    <image-util ref="imageUtil" @cropImg="cropImg" :fixed-number="[1, 1]"></image-util>
  </div>
</template>

<script>
import imageUtil from '../../common/imageUtil'
import goodsSpu from './goodsSpu'
import goodsSku from './goodsSku'
import goodsRichText from './goodsRichText'
export default {
  name: 'goods-auditing',
  data () {
    return {
      requestUrl: {
        goodUrl: '/goods/manage/get/goods/info/echo/audit/page',
        subBaseChange: '/goods/manage/modify/goods/info/audit/page',
        changeUrl: '/goods/manage/get/goods/info/modify/page'
      },
      // spu数据
      initSpuData: {},
      goodsId: null,
      isAuditing: false
    }
  },
  methods: {
    setImage (e) {
      this.$refs.imageUtil.setImage(e)
    },
    cropImg (data) {
      if (data.name === 'spu') {
        this.$refs.goodsSpu.setImgData(data.imgTime, data.blob)
      } else {
        this.$refs.goodsSku.setImgData(data.imgTime, data.blob)
      }
    },
    aARUtil (arr1, arr2) {
      let adds = []
      let removes = []
      if (!arr1[0]) {
        adds = arr2
      } else {
        let tempOld = []
        arr1.forEach(item => {
          tempOld['O' + item] = item
        })
        for (let i = 0; i < arr2.length; i++) {
          if (tempOld['O' + arr2[i]]) {
            // tempOld.splice('O' + spuData.labelIds[i], 1)
            tempOld['O' + arr2[i]] = null
            arr2.splice(i, 1)
            i--
          }
        }
        for (let j in tempOld) {
          if (tempOld[j] !== null) {
            removes.push(tempOld[j])
          }
        }
        adds = [...arr2]
      }
      return {adds, removes}
    },
    finishAuditing () {
      let params = this.$refs.goodsSku.getSubData()
      if (params === null) {
        this.$Message.error('请填写完整的价格')
        return
      }
      let data = {
        bcSetups: params.first,
        gpSetupDtos: params.second,
        rpSetups: params.third
      }
      let spuData = this.$refs.goodsSpu.getSpuData()
      if (spuData === null) {
        return
      }
      let labelArrs = this.aARUtil(this.initSpuData.goodsLabel, spuData.labelIds)
      let classifyArrs = this.aARUtil(this.initSpuData.selectClassify, spuData.goodsCategoryIds)
      let goodsMain = {
        id: this.goodsId,
        unitId: spuData.unitId,
        ...(spuData.goodsMain)
      }
      let removeMainImagePath = []
      if (spuData.deleteImage.gmImagePath) {
        removeMainImagePath = [spuData.deleteImage.gmImagePath[0]]
      }
      let detailContent = this.$refs.richText.getRichData()
      let provideGoodsUpdateInfoDto = {
        goodsMain,
        addLabelId: labelArrs.adds,
        removeLabelId: labelArrs.removes,
        addCategoryId: classifyArrs.adds,
        removeCategoryId: classifyArrs.removes,
        ...(data),
        detailContent,
        removeMainImagePath,
        isTrue: this.$route.query.change === undefined,
        priceTypeInfoDtos: params.priceTypeInfoDtos
      }
      let gmImages = []
      let formData = new FormData()
      if (spuData.addImages[1]) {
        formData.append('gmFirstImage', spuData.addImages.splice(1, 1)[0], 'file.jpg')
      }
      spuData.addImages.forEach(item => {
        gmImages.push(item)
      })
      gmImages.forEach((item, index) => {
        formData.append('gmImages', item, index + 'file.jpg')
      })
      formData.append('provideGoodsUpdateInfoDto', JSON.stringify(provideGoodsUpdateInfoDto))
      this.$ajax.post(this.requestUrl.subBaseChange, formData, {headers: {'Content-Type': 'multipart/form-data'}}).then(res => {
        if (res.data.success) {
          this.$Message.success(this.isAuditing ? '审核通过' : '修改成功')
          this.$router.push({path: '/goods/manage/modify/goods/info/audit/page'})
        }
      }).catch(() => {
        this.$Message.error('出现未知错误，审核未通过')
      })
    },
    setSpuData (res) {
      let mainImages = [null]
      res.goodsMainImagePaths.forEach(item => {
        mainImages.push('https://hycos-1257620396.file.myqcloud.com' + item)
      })
      mainImages.splice(1, 0, 'https://hycos-1257620396.file.myqcloud.com' + res.mainPath)
      this.initSpuData = {
        id: this.goodsId,
        ...res.gmInfoEcho,
        mainImages: mainImages,
        goodsLabel: res.goodsLabels,
        selectClassify: res.goodsCategory
      }
      this.$refs.goodsSpu.setInitData(this.initSpuData)
      this.$refs.richText.initData(res.detailContent)
    },
    setRichSku (data) {
      let skuData = {
        gsInfoEcho: data.gsInfoEcho
      }
      this.$refs.goodsSku.setInitData(skuData)
    },
    setChange (data, price) {
      let skuDataSetup = []
      let skuDataPrice = []
      let skuDataOnce = []
      let firstPrice = []
      let secondPrice = []
      let thirdPrice = []
      let temp = []
      price.forEach(item => {
        if (!temp['P' + item.goodsSkuId]) {
          temp['P' + item.goodsSkuId] = []
        }
        temp['P' + item.goodsSkuId].push({
          goodsSkuId: item.goodsSkuId,
          price: item.afterDiscountPrice / 100,
          branchCustomerId: item.setupId
        })
      })
      data.forEach(item => {
        if (item.discountType === 1) {
          firstPrice.push({
            id: item.goodsSkuId,
            stock: item.stock,
            warningStock: item.warningStock,
            costPrice: item.costPrice / 100,
            retailPrice: item.retailPrice / 100,
            skuStockType: item.skuStockType,
            goodsSkuName: item.goodsSkuName,
            sortWeight: item.sortWeight
          })
          item.belong = '1'
          skuDataSetup.push(item)
        } else if (item.discountType === 2) {
          secondPrice.push({
            id: item.goodsSkuId,
            stock: item.stock,
            warningStock: item.warningStock,
            costPrice: item.costPrice / 100,
            retailPrice: item.retailPrice / 100,
            skuStockType: item.skuStockType,
            goodsPriceSetups: this.fnSort(temp['P' + item.goodsSkuId]),
            goodsSkuName: item.goodsSkuName,
            sortWeight: item.sortWeight
          })
          item.belong = '2'
          skuDataPrice.push(item)
        } else if (item.discountType === 3) {
          thirdPrice.push({
            id: item.goodsSkuId,
            stock: item.stock,
            warningStock: item.warningStock,
            costPrice: item.costPrice / 100,
            retailPrice: item.retailPrice / 100,
            skuStockType: item.skuStockType,
            goodsSkuName: item.goodsSkuName,
            sortWeight: item.sortWeight
          })
          item.belong = '3'
          skuDataOnce.push(item)
        }
      })
      let params = {
        skuDataSetup,
        skuDataPrice,
        skuDataOnce,
        firstPrice,
        secondPrice,
        thirdPrice,
        isChange: true
      }
      this.$refs.goodsSku.setInitData(params)
    },
    fnSort (arr) {
      return arr.sort((a, b) => {
        return a.branchCustomerId - b.branchCustomerId
      })
    }
  },
  components: {
    imageUtil,
    goodsSpu,
    goodsSku,
    goodsRichText
  },
  created () {
    // /goods/manage/get/goods/info/echo/audit/page
    this.goodsId = this.$route.query.id
    if (!this.$route.query.change) {
      this.isAuditing = true
    }
  },
  mounted () {
    let change = this.$route.query.change
    if (change) {
      this.$ajax.get(this.requestUrl.changeUrl + '?goodsId=' + this.$route.query.id)
        .then(res => {
          if (res.data.success) {
            this.setSpuData(res.data.data.goodsInfoEchoAuditPageVo)
            this.setChange(res.data.data.goodsInfoEchoAuditPageVo.gsInfoEcho, res.data.data.gpsInfoList)
          }
        })
    } else {
      this.$ajax.get(this.requestUrl.goodUrl + '?goodsId=' + this.$route.query.id).then(res => {
        this.setSpuData(res.data.data)
        this.setRichSku(res.data.data)
      })
    }
  }
}
</script>

<style scoped>

</style>
